//
//  HD_NKM_Mediator.m
//  HDWuDaDaoServiceCenter
//
//  Created by HDNiuKuiming on 2017/5/12.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

#import "HD_NKM_Mediator.h"
#import "HD_NKM_Mediator+Post.h"
#import "Helper.h"

@interface HD_NKM_Mediator()
@property (strong, nonatomic) NSMutableDictionary *beacons;
@property (strong, nonatomic) CLLocationManager   *locationManager;
@property (strong, nonatomic) NSMutableDictionary *rangedRegions;


@end

@implementation HD_NKM_Mediator

#pragma mark -------- Init Methods ---------

+ (id)shareInstance
{
    static id shareMediator;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareMediator = [[self alloc] init];
    });
    
    return shareMediator;
}

- (instancetype)init
{
    self = [super init];
    
    if (self) {
        topBeaconArray = [[NSMutableArray alloc] initWithCapacity:2];
        
        [self resetConfig:nil]; // 使用默认的config
        [self initLocationManager];
        [self initBeacon]; // 初始化beacon
    }

    return self;
}

- (void)resetConfig:(HD_NKM_Mediator_Config *)config
{
    if (config == nil) {
        config = [HD_NKM_Mediator_Config new];
    }
    _beaconConfig = config;
}

- (void)initLocationManager
{
    CLLocationManager *locationM =  [[CLLocationManager alloc] init];
//    locationM = [[CLLocationManager alloc] init];
    locationM.delegate = self;
    [locationM requestWhenInUseAuthorization];
    self.locationManager = locationM;
    _isSystemLocateEnable = NO; // 系统默认是不允许定位的
}

- (void)initBeacon
{
    self.beacons = [[NSMutableDictionary alloc] init];
    self.rangedRegions = [[NSMutableDictionary alloc] init];
    
    for (NSUUID *uuid in [APLDefaults sharedDefaults].supportedProximityUUIDs) {
        CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:[uuid UUIDString]];
        self.rangedRegions[region] = [NSArray array];
    }
}

// 返回当前的通用距离阈值
- (NSString *)nowThre
{
    return [NSString stringWithFormat:@"%f", _beaconConfig.ThreshHold_Dis];
}

#pragma mark
#pragma mark -------- Location Delegate --------

// 开始收蓝牙号
- (void)startRangingAllRegions
{
    [self stopRangingAllRegions];
    
    for (CLBeaconRegion *region in self.rangedRegions) {
        [self.locationManager startRangingBeaconsInRegion:region];
    }
}

- (void)stopRangingAllRegions
{
    for (CLBeaconRegion *region in self.rangedRegions) {
        [self.locationManager stopRangingBeaconsInRegion:region];
    }
}

/** 定位服务状态改变时调用 */
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        {
            NSLog(@"用户还未决定授权，检查plist是否添加Privacy - Location When In Use Usage Description权限");
            break;
        }
        case kCLAuthorizationStatusRestricted:
        {
            NSLog(@"访问受限");
            break;
        }
        case kCLAuthorizationStatusDenied:
        {
            // 类方法，判断是否开启定位服务
            if ([CLLocationManager locationServicesEnabled]) {
                NSLog(@"定位服务开启，被拒绝");
            } else {
                NSLog(@"定位服务关闭，不可用");
            }
            
            if (_delegate == nil) {
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查是否开启定位权限，否则定位功能无法使用" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //打开隐私下的定位服务
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];
                [alertVC addAction:cancelAction];
                [alertVC addAction:alertAction];
                
//                UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
                UIViewController *rootVC = [Helper topViewController];

                [rootVC presentViewController:alertVC animated:YES completion:0];
            }
            else if ([_delegate respondsToSelector:@selector(userDeniedLocation)]) {
                [_delegate userDeniedLocation]; // 自己设定代理方法提示定位权限未开
            }
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways:
        {
            _isSystemLocateEnable = YES;
            NSLog(@"获得前后台授权");
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            _isSystemLocateEnable = YES;
            NSLog(@"获得前台授权");
            break;
        }
        default:
            break;
    }
}

// 只负责收集蓝牙号
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (beacons.count > 0 ) {
            self.rangedRegions[region] = beacons;
            [self.beacons removeAllObjects];
            
            NSMutableArray *allBeacons = [NSMutableArray new];
            for (NSArray *regionResult in [self.rangedRegions allValues]) {
                [allBeacons addObjectsFromArray:regionResult];
            }
            
            if (allBeacons.count > 0) {
                [self sortAndCalculateBeacon:allBeacons];
            }
        }
    });
}

// 计算多久没有收到蓝牙号，
- (void)noBeaconReceiveJudgeAction
{}

#pragma mark
#pragma mark -------- Dealloc Methods --------

- (void)cleanVarables
{
    [self.beacons removeAllObjects];
    self.beacons = nil;
    
    [self stopRangingAllRegions];
    self.locationManager = nil;
    
    [self.rangedRegions removeAllObjects];
    self.rangedRegions = nil;
    
    [topBeaconArray removeAllObjects];
    topBeaconArray    = nil;
}

- (void)dealloc
{
    [self cleanVarables];
    [self cleanBeaconTime];
}


@end
